//攻击伤害核算
//防御指数(x)将映射到函数空间  f 得出敌军攻击衰益率
//f: exp(-i*x)  (当 man*k <= i*x 时)
//f: exp(-i*x*i*x/(man*k))  (当 man*k > i*x 时)
//其中 i为常数，man为防守部队人数，k为常数，k与地块大小/部队装备水平相关

//常数计算参考：但defend_index = 50时，攻击衰益为50%。可得i = -ln(0.5)/50 = 0.013863
//常数计算参考：防御指数为25的地块防御总量刚好够5000人的部队。可得k = 25*0.013863/5000 = 0.000069315
var GetDefendRate = function(defendIndex, man){
	man = man || 0;
	
	var defendRate = 1;
	var k = 0.000069315;
	var i = 0.013863;
	var man_k = man * k;
	var defendIndex_i = defendIndex * i;
	if (man_k <= defendIndex_i)
		defendRate = Math.exp(-defendIndex_i);
	else
		defendRate = Math.exp(-defendIndex_i * defendIndex_i / man_k);
	return defendRate;
};

var AttackDamage = function(troopAttack, troopDefend, isCounterattack){
	var damage = {damageAttack:0, damageDefend:0};

	var defendIndex = campaign.zone.defend_index[campaign.troop[troopDefend].tileIndex];
	var man = campaign.troop[troopDefend].strength * campaign.troop[troopDefend].man_strength;
	var defendRate = GetDefendRate(defendIndex, man);
	
	var typeAttackid = campaign.troop[troopAttack].troop_type;
	var typeDefendid = campaign.troop[troopDefend].troop_type;
	
	damage.damageDefend = campaign.troop[troopAttack].strength
		* campaign.troop[troopAttack].level
		* campaign.troop[troopAttack].morale
		* campaign.troop[troopAttack].attack_efficiency[typeDefendid]
		* defendRate;
	
	if (isCounterattack == false)
		damage.damageAttack = 0;
	else
		damage.damageAttack = campaign.troop[troopDefend].strength
			* campaign.troop[troopDefend].level
			* campaign.troop[troopDefend].morale
			* campaign.troop[troopDefend].attack_efficiency[typeAttackid];
	
	return damage;
};

//修筑/破坏防御指数核算(防御指数为0~无穷)
//防御总量(x=当前防御总量+工程量)将映射到函数空间  f:sqrt(x) 得出防御指数
//工程量=man*j，man为部队人数，j为常数，与地块大小/科技水平相关
//防御指数对敌部队的攻击衰益请参见 AttackDamage()

//常数计算参考，5000人5天(30回合)可以使防御总量从0增加到自身所需容量(25)
//5000人，需要防御容量为5000*k=0.346575，相当于防御指数0.346575/i=25，工程量为25*25=625，每回合工程量定为20.83。j=20.83/5000=0.004166
var DefendIndexDiv = function(man, defend_index, isUp){
	var j = 0.00417;
	if (isUp == false)
		j = -j;
	var defendGross = defend_index * defend_index + (man * j);
	if (defendGross < 0)
		defendGross = 0;
	return Math.sqrt(defendGross) - defend_index;
};

//修筑/破坏通行障碍指数核算(通行障碍指数范围为0~100)
//障碍总量(x=当前障碍总量+工程量)将映射到函数空间  f:arctan(x)/PI*100+50 得出障碍指数
//工程量=man*l，man为部队人数，l为常数，与地块大小/科技水平相关
//一只移动能力为50的部队，需要一天时间，才能从通行障碍指数为20的tile，移动到通行障碍指数为30的tile。（50=20+30）

//常数计算参考，5000人2天(12回合)可以使障碍指数从50下降到25
//障碍指数50相当于障碍总量0，障碍指数25相当于障碍总量-1，工程量为1，每回合工程量为0.083333...，l=每回合工程量/5000=0.000016667
var PassIndexDiv = function(man, pass_index, isUp){
	var l = 0.000016667;
	if (isUp == false)
		l = -l;
	var passGross = Math.tan((pass_index - 50) / 100 * Math.PI) + (man * l);
	return Math.atan(passGross) / Math.PI * 100 + 50 - pass_index;
};